<template>
  <el-tree ref="msuiTree" :data="data" :show-checkbox="attrs.showCheckBox" :node-key="props.key" :props="props"
    :default-expanded-keys="attrs.expandedKeys" :default-checked-keys="val" @check-change="handleCheckChange"
    @current-change="currentChange" @node-click="nodeClick">
      <div class="tree-current" slot-scope="{ node, data }">
        <slot v-if="$scopedSlots.tree" name="tree" :data="data" :node="node"></slot>
        <span v-else>{{ node.label }}</span>
      </div>
  </el-tree>
</template>

<script>
export default {
  name: 'MsuiTree',
  props: {
    attrs: {
      type: Object,
      default: () => {
        return {}
      }
    },
    value: {
      default: () => {
        return []
      }
    }
  },
  watch: {
    val: {
      handler() {
        this.setCheckedKeys([])
      },
      deep: true
    }
  },
  mounted() {
    console.log(this)
  },
  computed: {
    val() {
      return this.value || []
    },
    props() {
      if (this.attrs.props) {
        return this.attrs.props
      } else {
        return {
          children: 'children',
          label: 'label',
          key: 'id'
        }
      }
    },
    data() {
      if (this.attrs.data) {
        return this.attrs.data
      } else {
        return [{
          id: 1,
          label: '一级 2',
          children: [{
            id: 3,
            label: '二级 2-1',
            children: [{
              id: 4,
              label: '三级 3-1-1'
            }, {
              id: 5,
              label: '三级 3-1-2',
              children: [{
                id: 6,
                label: '三级 4-1-1'
              }
              ]
            }]
          }]
        }]
      }
    }
  },
  methods: {
    handleCheckChange(val, b, c) {
      this.getCheckedKeys()
    },
    currentChange(a, b) {
      console.log(a, b)
    },
    setCheckedKeys(list) {
      this.$refs.msuiTree.setCheckedKeys(list)
    },
    getCheckedKeys() {
      const keyList = this.$refs.msuiTree.getCheckedKeys()
      this.$emit('input', keyList)
    },
    nodeClick(a,b,c) {
     if(this.attrs.nodeClick instanceof Function){
       this.attrs.nodeClick(a, b, c)
     }
     this.$emit('nodeClick', a, b, c)
    }
  }
}
</script>
<style scoped>
.tree-current {
  flex: 1;
  position: relative;
  display: flex;
  align-items: center;
}
</style>